<?php

namespace App\Http\Middleware;

use App\Model\User;
use Closure;
use Illuminate\Support\Facades\Route;

class Rbac
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //获取对象
        $user = User::find(session('uid'));
        //获取路由
        $route = Route::currentRouteName();

        if(!$user->can($route)){
            if($request->ajax()){
                return response()->json(['status'=>'error','msg'=>'没有访问权限']);
            }else{
                abort(403, 'Unauthorized action.');
            }
        }

        return $next($request);
    }
}
